from contextlib import contextmanager
from psycopg_pool import ConnectionPool
from dataclasses import make_dataclass


def dict_row_factory(cursor):
    field_names = [c.name for c in cursor.description]
    _dataclass = make_dataclass("Row", field_names)
    print("dataclass: ", _dataclass)

    def make_row(values):
        return _dataclass(*values)

    return make_row


dsn = "host=localhost dbname=examdb user=examdb"
dbconn_pool = ConnectionPool(dsn, min_size=4)


@contextmanager
def dblock():
    with dbconn_pool.connection() as conn:
        try:
            with conn.cursor(row_factory=dict_row_factory) as cur:
                yield cur
            conn.commit()
        except:
            conn.rollback()
            raise